import axios from 'axios'
import router from '@/router'
import {
  Message
} from 'element-ui'
import store from '@/store'
import {
  getToken
} from '@/utils/auth'
import {
  EasyjError
} from '@/utils/easyjError'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 300000 // 5m  request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(

  response => {
    const res = response.data
    if (res.code === undefined) { // download file
      return res
    }
    if (res.code !== 200) {
      if (res.code === 401) { // session invild
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      } else if (res.code === 403) {
        Message({
          message: res.message || '你没有权限，执行此操作！',
          type: 'error',
          duration: 5 * 1000
        })
      }
      /* 统一提示...
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      */
      return Promise.reject(new EasyjError(res.code || 500, res.message || 'Error'))
    } else {
      return res.data
    }
  },
  error => {
    let code = 0
    try {
      code = error.response.status
    } catch (e) {
      Message({
        message: '网络请求错误或超时',
        type: 'error',
        duration: 2500
      })
      return Promise.reject(error)
    }
    // alert(code)
    if (code === 401) { // session invild
      store.dispatch('user/resetToken').then(() => {
        location.reload()
      })
    } else if (code === 403) {
      router.push({
        path: '/403'
      })
    } else if (code === 404) {
      router.push({
        path: '/404'
      })
    } else {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }

)

export default service
